import { handleError, watch } from "vue";
import { WS_ADDRESS } from "../configs";
import { useStore } from "vuex";
import { ElMessage } from "element-plus";

function useWebsocket(handleMessage) {
  const store = useStore();
  const ws = new WebSocket(WS_ADDRESS);
  let pingInterval = null; // 定时器变量

  // 初始化连接
  const init = () => {
    bindEvent();
    startPing(); // 启动心跳机制
  };

  function bindEvent() {
    ws.addEventListener("open", handleOpen, false);
    ws.addEventListener("close", handleClose, false);
    ws.addEventListener("error", handleError, false);
    ws.addEventListener("message", handleMessage, false);
  }

  function handleOpen(e) {
    console.log("websocket open", e);
    startPing(); // 启动心跳机制
    ElMessage.success("WebSocket连接成功");
  }

  function handleClose(e) {
    console.log("websocket close", e);
    ElMessage.warning("WebSocket连接断开");
    stopPing(); // 连接关闭时停止心跳机制
  }

  function handleError(e) {
    console.log("websocket error", e);
    ElMessage.warning("WebSocket连接出错");
  }

  // 处理接收到的服务器消息
  function handleMessage(e) {
    // 处理服务器返回的消息
    var sd = JSON.parse(e.data);

    if (Object.keys(sd).length > 0) {
      // console.log(
      //   "%c [ sd ]-45",
      //   "font-size:13px; background:pink; color:#bf2c9f;",
      //   sd
      // );
      store.dispatch("updateAllPageData", sd);
    }

    // 重置定时器
    resetPing();
  }
  // 关闭连接。监听登出时定义关闭
  watch(
    () => store.state.websocketClose,
    (newvalue) => {
      // console.log("websocketClose", newvalue);
      if (newvalue) {
        if (ws) {
          ws.close();
          store.commit("setwebsocketClose", false);
          stopPing(); // 连接关闭时停止心跳机制
        }
      }
    }
  );

  function startPing() {
    pingInterval = setInterval(() => {
      if (ws.readyState === WebSocket.OPEN) {
        ws.send("ping"); // 发送心跳消息
      }
    }, 100000); // 设定心跳间隔时间，这里是1分钟
  }

  function stopPing() {
    clearInterval(pingInterval); // 停止心跳定时器
  }

  function resetPing() {
    clearInterval(pingInterval); // 取消当前定时器
    startPing(); // 启动一个新的定时器
  }

  // 初始化
  init();

  return ws;
}

export default useWebsocket;
